﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Common;
using DevExpress.XtraEditors;
using GMap.NET;
using GMap.NET.MapProviders;
using GMap.NET.WindowsForms;
using GMap.NET.WindowsForms.Markers;
using Model;
using System.Threading;

namespace TaxiDispatchClient
{
    public partial class GmapOverlayManagementForm : DevExpress.XtraEditors.XtraForm
    {
        public GmapOverlayManagementForm()
        {
            InitializeComponent();
            //Gridcontrol1

            searchLookUpEdit1.Properties.DataSource = MainForm.DtOverlayList;
            gridControl1.DataSource = MainForm.DtOverlayList;
            gridView1.Columns["id"].Visible = false;         
            gridView1.Columns["City"].Visible = false;
            gridView1.Columns["Latitude"].Visible = false;
            gridView1.Columns["Longitude"].Visible = false;
            gridView1.Columns["Star"].Visible = false;
            gridView1.Columns["Remark"].Visible = false;
            gridView1.Columns["OverlayName"].Caption = "名称";
            gridView1.Columns["OverlayName"].Width = 170;
            gridView1.Columns["Overlaytype"].Caption = "类型";
            gridView1.Columns["Overlaytype"].Width = 40;
            gridView1.RowHeight = 24;
           

            //mainMap
            mainMap.Manager.Mode = AccessMode.ServerAndCache;
            mainMap.MapProvider = GMapProviders.GoogleChinaMap;
            double theCenterLat = Properties.Settings.Default.MainMapLat;
            double theCenterLng = Properties.Settings.Default.MainMapLng;
            mainMap.MaxZoom = 18;
            mainMap.MinZoom = 8;
            mainMap.Zoom = 12;
            mainMap.Position = new PointLatLng(theCenterLat, theCenterLng);
            mainMap.DragButton = MouseButtons.Left;
            _overlay = new GMapOverlay("overlay");
            mainMap.Overlays.Add(_overlay);

            // trackBarControl_MapZoom
            trackBarControl1.Properties.Minimum = mainMap.MinZoom;
            trackBarControl1.Properties.Maximum = mainMap.MaxZoom;
            trackBarControl1.Value = int.Parse(mainMap.Zoom.ToString());
           // this.WindowState = FormWindowState.Maximized;
        }
        private void GmapOverlayManagementForm_Load(object sender, EventArgs e)
        {
            DrawOverlay();
        }

        private readonly GMapOverlay _overlay;
        private PointLatLng _pointLatLng;
        private int _id;       
        private bool _isChanged = false;

        private void DrawOverlay()
        {
             _overlay.Markers.Clear();            
            if (MainForm.DtOverlayList.Rows.Count < 1) return;
            for (int i = 0; i < MainForm.DtOverlayList.Rows.Count; i++)
            {
                AddMarkerToOverlay(MainForm.DtOverlayList.Rows[i]);
            }
            gridControl1.DataSource = MainForm.DtOverlayList;
            searchLookUpEdit1.Properties.DataSource = MainForm.DtOverlayList;
        }

        private void AddMarkerToOverlay(DataRow row)
        {
            if(row ==null) return;
            Bitmap obj = GetMarkerBitmap(row["Overlaytype"].ToString());
            PointLatLng point = new PointLatLng(double.Parse(row["Latitude"].ToString()),
                double.Parse(row["Longitude"].ToString()));
            GMarkerGoogle gMarker = new GMarkerGoogle(point, obj)
            {
                ToolTipText =
                row["OverlayName"] +Environment.NewLine+
                "类型："+row["Overlaytype"]+Environment.NewLine+
                "星级：" + row["Star"] + Environment.NewLine + "备注：" + row["Remark"],
                ToolTipMode = MarkerTooltipMode.OnMouseOver,
                Tag = row["id"]
            };
            _overlay.Markers.Add(gMarker);            
        }       

        #region  GetMarkerBitmap  根据标记类型获得图标
        public static Bitmap GetMarkerBitmap(string  type)
        {
            Bitmap obj = Properties.Resources.overlay_else;
            switch (type)
            {
                case "餐饮":
                    obj = Properties.Resources.overlay_eatDrank;
                    break;
                case "超市":
                    obj = Properties.Resources.overlay_market;
                    break;

                case "酒店":
                    obj = Properties.Resources.overlay_restaurant;
                    break;

                case "银行":
                    obj = Properties.Resources.overlay_bank;
                    break;

                case "小区":
                    obj = Properties.Resources.overlay_live;
                    break;

                case "学校":
                    obj = Properties.Resources.overlay_school;
                    break;

                case "医院":
                    obj = Properties.Resources.overlay_hospital;
                    break;

                case "景点":
                    obj = Properties.Resources.overlay_park;
                    break;

                case "加油站":
                    obj = Properties.Resources.overlay_gas;
                    break;

                case "停车场":
                    obj = Properties.Resources.overlay_parkingArea;
                    break;
                case "休闲娱乐":
                    obj = Properties.Resources.overlay_play;
                    break;
                case "政府机构":
                    obj = Properties.Resources.overlay_goverment;
                    break;
                case "其他":
                    obj = Properties.Resources.overlay_else;
                    break;
            }    
            
                
            return obj;
        }
#endregion

        private void mainMap_OnMapZoomChanged()
        {
            trackBarControl1.Value = (int)mainMap.Zoom;
        }

        private void trackBarControl1_Properties_ValueChanged(object sender, EventArgs e)
        {
            mainMap.Zoom = trackBarControl1.Value;
        }

        private void mainMap_OnMarkerClick(GMapMarker item, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                popupMenu_right.ShowPopup(MousePosition);
                barBtn_addMarker.Enabled = false;
                barBtn_deleteMarker.Enabled = true;
                barBtn_editMarker.Enabled = true;
                _id = int.Parse(item.Tag.ToString());
            }
        }

        private void mainMap_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                popupMenu_right.ShowPopup(MousePosition);
                barBtn_addMarker.Enabled = true;
                barBtn_deleteMarker.Enabled = false;
                barBtn_editMarker.Enabled = false;
                _pointLatLng = mainMap.FromLocalToLatLng(e.X, e.Y);
            }
        }

        private void barBtn_addMarker_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GmapOverlayAddEditForm addEditForm = new GmapOverlayAddEditForm(_pointLatLng.Lng, _pointLatLng.Lat);
            addEditForm.ShowDialog();
            if(addEditForm.DialogResult==DialogResult.OK)
            {
                DrawOverlay();
                _isChanged = true;
            }
        }

        private void barBtn_editMarker_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            GmapOverlayAddEditForm addEditForm = new GmapOverlayAddEditForm(_id);
            addEditForm.ShowDialog();
            if (addEditForm.DialogResult == DialogResult.OK)
            {
                DrawOverlay();
                _isChanged = true;
            }
        }


        private void barBtn_deleteMarker_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if(XtraMessageBox.Show("确定删除该标记？","警告",MessageBoxButtons.YesNo)== DialogResult.Yes)
            {
              if(MainForm.PositionService.GmapoverlayDelete(_id))
              {
                  GMapMarker g = _overlay.Markers.FirstOrDefault(
                                   gMapMarker => gMapMarker.Tag.ToString() == _id.ToString());
                  _overlay.Markers.Remove(g);                  
                  int rowindex = -1;
                  for (int i = 0; i < MainForm.DtOverlayList.Rows.Count; i++)
                  {
                      if (MainForm.DtOverlayList.Rows[i]["id"].ToString() == _id.ToString())
                      {
                          rowindex = i;
                      }
                  }
                  if (rowindex>-1)
                  {
                      MainForm.DtOverlayList.Rows.RemoveAt(rowindex);    
                  }                  
                  gridControl1.DataSource = MainForm.DtOverlayList;
                  searchLookUpEdit1.Properties.DataSource = MainForm.DtOverlayList;
                  XtraMessageBox.Show("标记已成功删除！");
                  _isChanged = true;
                  return;
              }
              XtraMessageBox.Show("标记删除失败！");
            }                                    
        }

           

        private void barBtn_refresh_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            DrawOverlay();
        }

        

        private void gridView1_RowClick(object sender, DevExpress.XtraGrid.Views.Grid.RowClickEventArgs e)
        {
            DataRow dr = this.gridView1.GetFocusedDataRow();//
            if (dr != null)
            {
                if (e.Button == MouseButtons.Right)
                {
                    _id = int.Parse(dr["id"].ToString());
                    popupMenu_right.ShowPopup(Control.MousePosition);
                    barBtn_addMarker.Enabled = false;
                    barBtn_deleteMarker.Enabled = true;
                    barBtn_editMarker.Enabled = true;
                }
                else
                {
                    PointLatLng p = new PointLatLng(double.Parse(dr["Latitude"].ToString()), double.Parse(dr["Longitude"].ToString()));
                    mainMap.Position = p;
                }
            }
        }

        private void GmapOverlayManagementForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            if(_isChanged)
            {
                this.DialogResult = DialogResult.Yes;
            }
        }

        private void searchLookUpEdit1_EditValueChanged(object sender, EventArgs e)
        {
            DataRow dr = searchLookUpEdit1.Properties.View.GetFocusedDataRow();
            if (dr == null) return;
            PointLatLng p = new PointLatLng(double.Parse(dr["Latitude"].ToString()), double.Parse(dr["Longitude"].ToString()));
            mainMap.Position = p;
        }



        private void simpleButton_goto_Click(object sender, EventArgs e)
        {
            MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
        }


        private void textBoxGeo_KeyPress(object sender, KeyPressEventArgs e)
        {
            if ((Keys)e.KeyChar == Keys.Enter)
            {
                MainMapSetCurrentPositionByKeywords(textBoxGeo.Text);
            }

        }
        private void MainMapSetCurrentPositionByKeywords(string positionName)
        {
            GeoCoderStatusCode status = mainMap.SetPositionByKeywords(positionName);
            if (status != GeoCoderStatusCode.G_GEO_SUCCESS)
            {
                MessageBox.Show("谷歌地图找不到: '" + textBoxGeo.Text + "', reason: " + status.ToString(), "GMap.NET", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
            }           
        }      

        #region 窗体控件效果
        private void pictureEdit_exit_MouseHover(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexit;
            Cursor = Cursors.Hand;
        }

        private void pictureEdit_exit_MouseLeave(object sender, EventArgs e)
        {
            pictureBox1.Image = Properties.Resources.snedSmsexitPressDown;
            Cursor = Cursors.Arrow;
        }
        private void pictureBox1_Click(object sender, EventArgs e)
        {
            Close();
        }


        Point _mouseOff;
        bool _leftFlag;
        private void Form_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                _mouseOff = new Point(-e.X, -e.Y);
                _leftFlag = true;
            }
        }

        private void Form_MouseMove(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                Point mouseSet = Control.MousePosition;
                mouseSet.Offset(_mouseOff.X, _mouseOff.Y);
                Location = mouseSet;
            }
        }

        private void Form_MouseUp(object sender, MouseEventArgs e)
        {
            if (_leftFlag)
            {
                _leftFlag = false;
            }
        }
        private void Form_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                Close();
            }
        }
        #endregion

    }
}